#include "main.h"
#include <string.h>

#define wiLED

#define I2C_DATA_LENGTH  9
#define I2C_ADDRESS      0x50 << 1
#define I2C_SPEEDCLOCK   100000
#define I2C_DUTYCYCLE    I2C_DUTYCYCLE_16_9

#define REG_COMM      0X00
#define REG_SETUP     0X10
#define REG_CLOCK     0X20
#define REG_DATA      0X30
#define REG_TEST      0X40
#define REG_ZERO      0X60
#define REG_FULL      0X70

#define WRITE         0X00
#define READ          0X08

#define CH_0          0
#define CH_1          1
#define MD_CAL_SELF   0x40
#define BIPOLAR       0
#define UNIPOLAR      0x4
#define BUF_NO        0
#define BUF_EN        0x2

I2C_HandleTypeDef I2cHandle;
SPI_HandleTypeDef Spi1Handle;

#define BUF_LEN 32
uint8_t spiRxBuffer[BUF_LEN] = {0};
uint8_t spiTxBuffer[BUF_LEN] = {0};
uint32_t payload[3];

uint8_t status = 0;
uint8_t channel_flag = 0;
uint16_t counter = 0;

uint32_t voltage = 300;
uint32_t current = 600;

static void I2C_Send(void);
static void APP_SystemClockConfig(void);
static void SPI_Write(uint8_t length);

static void APP_ConfigADC(void) {
	spiTxBuffer[0] = 0xff;
	spiTxBuffer[1] = 0xff;
	spiTxBuffer[2] = 0xff;
	spiTxBuffer[3] = 0xff;
	spiTxBuffer[4] = 0xff;
	spiTxBuffer[5] = 0xff;
	
	spiTxBuffer[6] = REG_CLOCK | CH_0;
	spiTxBuffer[7] = 0x08 | 0x04;
//	SPI_Write(2);
//	HAL_Delay(1);
	
	spiTxBuffer[8] = REG_CLOCK | CH_1;
	spiTxBuffer[9] = 0x08 | 0x04;
//	SPI_Write(2);
//	HAL_Delay(1);
	
	spiTxBuffer[10] = REG_TEST;
	spiTxBuffer[11] = 0x01;
//	SPI_Write(2);
//	HAL_Delay(1);
	
	spiTxBuffer[12] = REG_SETUP | CH_0;
	spiTxBuffer[13] = 0x40 | 0x04 | 0x02;
//	SPI_Write(2);
//	HAL_Delay(1);
	
	spiTxBuffer[14] = REG_SETUP | CH_1;
	spiTxBuffer[15] = 0x40 | 0x04 | 0x02;
	
	while (Spi1Handle.State != HAL_SPI_STATE_READY);
	if (HAL_SPI_TransmitReceive_IT(&Spi1Handle, (uint8_t *)spiTxBuffer, (uint8_t *)spiRxBuffer, 16) != HAL_OK) APP_Error_Handler();
}

void APP_GPIO_Init(void) {
  GPIO_InitTypeDef  GPIO_InitStruct = {0};

  __HAL_RCC_GPIOA_CLK_ENABLE();
	
  GPIO_InitStruct.Pin   = GPIO_PIN_4;
  GPIO_InitStruct.Mode  = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull  = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin   = GPIO_PIN_7;
  GPIO_InitStruct.Pull  = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	GPIO_InitStruct.Mode  = GPIO_MODE_IT_FALLING;
	
	HAL_NVIC_SetPriority(EXTI4_15_IRQn, 0x0F, 0);
  HAL_NVIC_EnableIRQ(EXTI4_15_IRQn);
	
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
	HAL_Delay(10);
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
	#ifdef wiLED
  __HAL_RCC_GPIOB_CLK_ENABLE();
  GPIO_InitStruct.Pin   = GPIO_PIN_3;
  GPIO_InitStruct.Mode  = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull  = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET);
	#endif
}

int main(void) {
  HAL_Init();
  APP_SystemClockConfig();
	APP_GPIO_Init();
	
  I2cHandle.Instance             = I2C;
  I2cHandle.Init.ClockSpeed      = I2C_SPEEDCLOCK; 
  I2cHandle.Init.DutyCycle       = I2C_DUTYCYCLE;
  I2cHandle.Init.OwnAddress1     = I2C_ADDRESS;
  I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  I2cHandle.Init.NoStretchMode   = I2C_NOSTRETCH_DISABLE;
	if (HAL_I2C_Init(&I2cHandle) != HAL_OK) APP_Error_Handler();
	
	Spi1Handle.Instance               = SPI1;
  Spi1Handle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
  Spi1Handle.Init.Direction         = SPI_DIRECTION_2LINES;
  Spi1Handle.Init.CLKPolarity       = SPI_POLARITY_HIGH;
  Spi1Handle.Init.CLKPhase          = SPI_PHASE_2EDGE;
  Spi1Handle.Init.DataSize          = SPI_DATASIZE_8BIT;
  Spi1Handle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
  Spi1Handle.Init.NSS               = SPI_NSS_SOFT;
  Spi1Handle.Init.Mode              = SPI_MODE_MASTER;
  if (HAL_SPI_DeInit(&Spi1Handle) != HAL_OK) APP_Error_Handler();
  if (HAL_SPI_Init(&Spi1Handle) != HAL_OK) APP_Error_Handler();
	
	counter = 0;
	APP_ConfigADC();
	while(1) {
		if (HAL_I2C_GetState(&I2cHandle) == HAL_I2C_STATE_READY) {
			I2C_Send();
		}
		if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_7) == GPIO_PIN_RESET) {
			SPI_Write(2);
			voltage = spiRxBuffer[0];
		}
		HAL_Delay(10);
		counter += 1;
		#ifdef wiLED
		HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_3);
		#endif
	}
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
	if(GPIO_Pin == GPIO_PIN_7){
		status += 1;
	}
}

static void SPI_Write(uint8_t length) {
	while (Spi1Handle.State != HAL_SPI_STATE_READY);
	spiTxBuffer[0] = REG_DATA | CH_1 | READ;
	if (HAL_SPI_TransmitReceive_IT(&Spi1Handle, (uint8_t *)spiTxBuffer, (uint8_t *)spiRxBuffer, length) != HAL_OK) APP_Error_Handler();
}

static void I2C_Send(void) {
	payload[0] = voltage;
	payload[1] = current;
	payload[2] = status;
	while (HAL_I2C_Slave_Transmit_IT(&I2cHandle, (uint8_t *)payload, I2C_DATA_LENGTH) != HAL_OK) APP_Error_Handler();
}

static void APP_SystemClockConfig(void) {
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_24MHz;
  RCC_OscInitStruct.HSEState = RCC_HSE_OFF;
  RCC_OscInitStruct.LSIState = RCC_LSI_OFF;

  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) APP_Error_Handler();

  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
	
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) APP_Error_Handler();
}

void HAL_MspInit(void) {
  __HAL_RCC_SYSCFG_CLK_ENABLE();
  __HAL_RCC_PWR_CLK_ENABLE();
}


void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  __HAL_RCC_SYSCFG_CLK_ENABLE();
  __HAL_RCC_I2C_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /**I2C GPIO Configuration
  PA3     ------> I2C1_SCL
  PA2     ------> I2C1_SDA
  */
  GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_3;
  GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF12_I2C;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  /*I2C*/
  __HAL_RCC_I2C_FORCE_RESET();
  __HAL_RCC_I2C_RELEASE_RESET();

  /* I2C1 interrupt Init */
  HAL_NVIC_SetPriority(I2C1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(I2C1_IRQn);
}

 void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi){
	GPIO_InitTypeDef  GPIO_InitStruct = {0};

	__HAL_RCC_GPIOF_CLK_ENABLE();
	__HAL_RCC_GPIOA_CLK_ENABLE();
	__HAL_RCC_SPI1_CLK_ENABLE();

	/* SPI1
	PA5   ------> SPI1_SCK
	PA1   ------> SPI1_MOSI
	PA0   ------> SPI1_MISO
	PF1   ------> SPI1_CS
	*/

	/*SCK*/
	GPIO_InitStruct.Pin       = GPIO_PIN_5;
	GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
	if (hspi->Init.CLKPolarity == SPI_POLARITY_LOW)
	{
		GPIO_InitStruct.Pull = GPIO_PULLDOWN;
	}
	else
	{
		GPIO_InitStruct.Pull = GPIO_PULLUP;
	}
	GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_VERY_HIGH;
	GPIO_InitStruct.Alternate = GPIO_AF0_SPI1;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

	/*SPI NSS*/
	GPIO_InitStruct.Pin = GPIO_PIN_1;
	GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
	GPIO_InitStruct.Alternate = GPIO_AF10_SPI1;
	HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);


	/*SPI MISO/MOSI*/
	GPIO_InitStruct.Pin       = GPIO_PIN_0 | GPIO_PIN_1;
	GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull      = GPIO_NOPULL;
	GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_VERY_HIGH;
	GPIO_InitStruct.Alternate = GPIO_AF10_SPI1;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

	/*NVIC*/
	HAL_NVIC_SetPriority(SPI1_IRQn, 1, 0);
	HAL_NVIC_EnableIRQ(SPI1_IRQn);
 }

void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) {
  if (hspi->Instance == SPI1) {
    __HAL_RCC_SPI1_FORCE_RESET();
    __HAL_RCC_SPI1_RELEASE_RESET();
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_5 );
    HAL_GPIO_DeInit(GPIOF, GPIO_PIN_1);
    HAL_NVIC_DisableIRQ(SPI1_IRQn);
  }
}

void APP_Error_Handler(void) {
  /* Infinite loop */
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line)  */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
